/**      
*  @Title:  RegistercController.java  
*  @Package  com.zjdiepu.www.rest.api.pub.action  
*    
*  @author  zhangpp
*  @date  2017年10月20日  上午10:24:01  
*  @version  V1.0      
*/
package com.zjdiepu.www.rest.api.pub.action;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.commpent.handler.TokenUserHelper;
import com.zjdiepu.www.dao.third.BaseShortMessageMapper;
import com.zjdiepu.www.ibiz.zpp.AppNewsService;
import com.zjdiepu.www.ibiz.zpp.PublicService;
import com.zjdiepu.www.ibiz.zpp.SystemService;
import com.zjdiepu.www.model.third.dto.BaseShortMessage;
import com.zjdiepu.www.rest.api.pub.ext.AppSwitchExt;
import com.zjdiepu.www.rest.api.pub.ext.SendOutPhoneExt;
import com.zjdiepu.www.util.CommonUtil;
import com.zjdiepu.www.util.PasswordUtil;

/**            
 *  项目名称：diepu-parent-rest      
 *  类名称：RegistercController      
 *  类描述：      
 *  创建人：zhangpp
 *  创建时间：2017年10月20日  上午10:24:01      
 *  修改人：zhangpp
 *  修改时间：2017年10月20日  上午10:24:01      
 *  修改备注：      
 *  @version  V1.0          
 */
@RestController
@RequestMapping(value= "RegistercController", produces="application/json;charset=UTF-8")
@Api(tags = {"移动端API，作者：张虹剑   电话：15158822934，心情：捐躯赴国难，视死忽如归"}, produces="application/json;charset=UTF-8")
public class RegistercController  extends BaseController{
	
	@Resource
    private TokenUserHelper tokenUserHelper;
	
	@Resource
	private PublicService publicService;
	
	@Resource
	private BaseShortMessageMapper baseShortMessageMapper;
	
	@Resource
	private AppNewsService appNewsService;
	
	@Resource
	private SystemService systemService;
	
	
	//移动端调用的开关
	@ApiOperation(value = "移动端调用的开关，作者：张虹剑",response = Integer.class, httpMethod="POST")
	@ApiResponses({
		@ApiResponse(code = 100100, message = "switch_code = 1 注册开关"),
	})
	@RequestMapping(value="appSwitch",method = RequestMethod.POST, produces="application/json;charset=UTF-8")
	public Map<String, Object> appSwitch(@RequestBody String requestJsonString) throws Exception
	{
		Map<String, Object> maps = success();
		
		if(StringUtils.isBlank(requestJsonString))
		{
			throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(),ResultFlagType.PARAM_EMPTY.getValue());
		}
		AppSwitchExt appSwitchExt = new Gson().fromJson(requestJsonString, AppSwitchExt.class);
		String switchCode = appSwitchExt.getSwitchCode();
		
		if(StringUtils.isBlank(switchCode))
		{
			throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(),ResultFlagType.PARAM_EMPTY.getValue());
		}
		String sqlXmls = "select t.id,t.uname,t.switchs,t.switch_code from base_switch t where t.dp_status = 1 and t.switch_code = '"+switchCode+"'";
		List<Map<String, String>> result = publicService.queryWhereSql(sqlXmls);
		maps.put("result", result);
		return maps;
	}
	
	
	//验证验证码是否正确并且在10分钟之内
	@ApiOperation(value = "验证验证码是否正确并且在10分钟之内，作者：张虹剑",response = Integer.class, httpMethod="POST")
	@ApiResponses({
		@ApiResponse(code = 100300, message = "输入的验证码不存在"),
		@ApiResponse(code = 100400, message = "验证超过10分钟以上"),
		@ApiResponse(code = 100500, message = "两次密码输入不一致"),
		@ApiResponse(code = 100600, message = "判断当前手机号码有没有被注册过")
	})
	@RequestMapping(value="verificationPhone",method = RequestMethod.POST, produces="application/json;charset=UTF-8")
	public Map<String, Object> verificationPhone(@RequestBody String requestJsonString) throws Exception
	{
		Map<String, Object> maps = success();
		if(StringUtils.isBlank(requestJsonString))
		{
			throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(),ResultFlagType.PARAM_EMPTY.getValue());
		}
		
		SendOutPhoneExt sendOutPhoneExt = new Gson().fromJson(requestJsonString, SendOutPhoneExt.class);
		String phone = sendOutPhoneExt.getPhone();
		String phoneCode = sendOutPhoneExt.getPhoneCode();
		String pass = sendOutPhoneExt.getPass();
		String passNew = sendOutPhoneExt.getPassNew();
		
		if(StringUtils.isBlank(phone) || StringUtils.isBlank(phoneCode) || StringUtils.isBlank(pass) || StringUtils.isBlank(passNew))
		{
			throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(),ResultFlagType.PARAM_EMPTY.getValue());
		}
		
		//判断当前手机号码有没有被注册过
		String sqlXmls = "select count(t.id) count from sys_user t where t.login_name = '"+phone+"' limit 1";
		int count = publicService.countSqlXmls(sqlXmls);
		if(count > 0)
		{
			throw new BaseException("100600","当前手机号码已经被注册");
		}
		
		//验证输入的验证码是否存在
		sqlXmls = "select count(t.id) count from base_short_message t where t.phone = '"+phone+"' and t.phone_code = '"+phoneCode+"' ";
		count = publicService.countSqlXmls(sqlXmls);
		if(count < 1)
		{
			throw new BaseException("100300","输入的验证码不存在");
		}
		
		//判断验证码是否在10分钟之内
		sqlXmls = "select ((unix_timestamp(now()) - t.created) / 60) created from base_short_message t where t.phone = '"+phone+"' and t.phone_code = '"+phoneCode+"' order by t.created desc limit 1";
		List<Map<String, String>>  result = publicService.queryWhereSql(sqlXmls);
		if(null == result || 0 == result.size())
		{
			throw new BaseException("100300","输入的验证码不存在");
		}
		
		Map<String, String> resultT = result.get(0);
		JSONObject json = CommonUtil.getJSONObject(resultT);
		double created = json.getDouble("created");
		if(created > 10)
		{
			throw new BaseException("100400","验证超过10分钟以上");
		}
		
		//验证两次密码是否一致
		if(!pass.equals(passNew))
		{
			throw new BaseException("100500","两次密码输入不一致");
		}
		
		String orgId = "896332b2e1654700850c748e77fc4dd0";
		String roleId = "be0de349f19844c6a68a07c936d47c30";
		String salersmanId = "0e311cab4cc54c3485df03d943a92600";
		String salersmanCode = "00340010002"; 
		String codeUnit = "00340010002";
		String idUnit = "0e311cab4cc54c3485df03d943a92600";
		
		//加密
		pass = PasswordUtil.getDbPasswordForMd5(phone, pass);
		Map<String, String> result1 = systemService.register(phone, pass, orgId, roleId,salersmanId,salersmanCode,codeUnit,idUnit);
		maps.put("result", result1);
		return maps;
	}
	
	//发送验证码
	@ApiOperation(value = "发送验证码，作者：张虹剑 ",response = Integer.class, httpMethod="POST")
	@RequestMapping(value="SendOutPhone",method = RequestMethod.POST, produces="application/json;charset=UTF-8")
	public Map<String, Object> SendOutPhone(@RequestBody String requestJsonString) throws Exception
	{
		Map<String, Object> maps = success();
		if(StringUtils.isBlank(requestJsonString))
		{
			throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(),ResultFlagType.PARAM_EMPTY.getValue());
		}
		
		SendOutPhoneExt sendOutPhoneExt = new Gson().fromJson(requestJsonString, SendOutPhoneExt.class);
		String phone = sendOutPhoneExt.getPhone();
		
		if(StringUtils.isBlank(phone))
		{
			throw new BaseException(ResultFlagType.PARAM_EMPTY.getCode().toString(),ResultFlagType.PARAM_EMPTY.getValue());
		}
		
		//发送验证码
		int code = (int)((Math.random()*9+1)*1000);
		appNewsService.diepuFaSongDuanXin1(phone, "注册验证码是"+String.valueOf(code), "请在10分钟之内完成注册，");
		
		//插入数据库
		BaseShortMessage baseShortMessage = new BaseShortMessage();
		baseShortMessage.initInsertData("00000000000000000000000000000000", "移动端注册发送验证码");
		baseShortMessage.setPhone(phone);
		baseShortMessage.setPhoneCode(code);
		baseShortMessage.setMessage("手机移动端注册");
		baseShortMessage.setFlag(ResultFlagType.SUCCESS.getCode());
		baseShortMessage.setDpType(1);
		baseShortMessageMapper.insert(baseShortMessage);
		return maps;
	}
}
